import Vue from "vue";
import VueRouter from "vue-router";
import Detail from "@/views/Detail.vue";
import Layout from "@/views/Layout.vue";
import Login from "@/views/Login.vue";
import Register from "@/views/Register.vue";
import Like from "@/views/Like";
import Article from "@/views/Article";
import Collect from "@/views/Collect";
import User from "@/views/User";
import { getToken } from "@/utils/storage";

Vue.use(VueRouter);

const routes = [
  {
    path: "/detail:id",
    component: Detail,
  },
  {
    path: "/",
    component: Layout,
    redirect: "/article",
    children: [
      // 这里可以简写
      // 子路由路径 只需要提供一个路径名即可
      { path: "article", component: Article },
      { path: "like", component: Like },
      { path: "collect", component: Collect },
      { path: "user", component: User },
    ],
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/register",
    component: Register,
  },
];

const router = new VueRouter({
  routes,
});

const WHITE_LIST = ["/login", "/register"];

router.beforeEach((to, from, next) => {
  if (getToken()) {
    next();
  } else {
    if (WHITE_LIST.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
